import json

from funcall.AbstractFunCall import AbstractFunCall, fun_call_log_debug, FUN_CALL_REMARK

from conf.config import AppConf
from funcall.FuncallInfo import FuncallInfo
from funcalltools.file_utils import fc_write_file, fc_read_file
from funcall.funcall_result import FuncallResult
from funcalltools.json_utils import to_json
from utils.log_utils import log_title


class access_www_fun_call(AbstractFunCall):
    def __init__(self):
        self.name = "access_www"
        self.description = "访问互联网,只会返回文本信息"

        work_dir = AppConf['ai']['work_dir']
        # 因为获取当前时间无需输入参数，因此parameters为空字典
        self.parameters = {
            "type": "object",
            "properties": {
                "url": {
                    "type": "string",
                    "description": f"要访问的网址"
                },
                "remark": {
                    "type": "string",
                    "description": FUN_CALL_REMARK
                }
            }
        }
        self.required = [
            "remark",
            "url"
        ]

    def action(self, jsonRoot):
        arg_tmp = jsonRoot['url']
        # 搜索关键字 "Full Stack Developer"
        funcallInfo = FuncallInfo(description="access_www", req_args=arg_tmp)
        funcallInfo.remark=jsonRoot['remark']
        import requests
        response = requests.get(arg_tmp)
        if response.status_code == 200:
            content_tmp = response.text
            funcallResult = FuncallResult(msg="成功", content=content_tmp)
        else:
            content_tmp=(f"检索页面失败。状态代码: {response.status_code}")
            funcallResult = FuncallResult(msg="", error=content_tmp)
        funcallInfo.log_text=content_tmp
        fun_call_log_debug(funcallInfo)
        #html2text
        return funcallResult.to_json()


if __name__ == '__main__':
    import logging

    print("setting logging level")
    logging.basicConfig(level=logging.NOTSET)
    logging.debug("asus")
    # 创建一个GetCurrentWeatherFunCall对象
    cw = access_www_fun_call()

    # 调用GetCurrentWeatherFunCall对象的call方法
    args = {"url": "http://baidu.com"}
    result = cw.call(args)

    # 打印结果
    print((result))
